package com.dl.study.config.shiroconfig;

import com.dl.study.config.jwt.CustomCacheManager;
import com.dl.study.config.jwt.JwtFilter;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: user
 * @Date: 2021/10/22 10:12
 * @Description:
 */
@Configuration
public class ShiroConfig {


    /**
     * 排除过滤url
     */
    @Value("${token.excludeUrl}")
    private String excludeUrl;

    /**
     * RefreshToken过期时间
     */
    @Value("${token.refreshTokenExpireTime}")
    private long refreshTokenExpireTime;

    /**
     * 是否需要开启任何请求必须登录才可访问
     */
    @Value("${token.mustLoginFlag}")
    private boolean mustLoginFlag;


    /**
     * 步骤1：配置shiro,将所有请求提交给shiro去管理
     * 添加shiro自带的内置过滤器
     * 常用过滤器：
     * anon:无需认证(登录)即可访问
     * authc:必须认证才可以访问
     * user:如果使用rememberMe的功能可以直接访问
     * perms:该资源必须获得资源权限才能使用
     * role:该资源必须得到用户角色权限才能访问
     *
     * @param securityManager 安全管理器
     * @return
     */


    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        ///这里不使用shiro自带的拦截器，使用自定义的jwt来进行拦截
        Map<String, Filter> filterMap = new HashMap<>(16);
        filterMap.put("jwt", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

//        filterChainDefinitionMap.put("/css/**", "anon");
//        filterChainDefinitionMap.put("/js/**", "anon");
//        filterChainDefinitionMap.put("/fonts/**", "anon");
//        filterChainDefinitionMap.put("/img/**", "anon");
//        filterChainDefinitionMap.put("/logout", "logout");

        //filterChainDefinitionMap.put("/webjars/**", "anon");
        // 查看SQL监控（druid）
//        filterChainDefinitionMap.put("/druid/**", "anon");
        // 首页和登录页面
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        // swagger
//        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
//        filterChainDefinitionMap.put("/swagger-resources", "anon");
//        filterChainDefinitionMap.put("/v2/api-docs", "anon");
//        filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");
        //拦截请求使用我们自己定义的拦截器
        filterChainDefinitionMap.put("/**", "jwt");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }


    /**
     * 步骤2.配置SecurityManager,并且将安全管理器作为参数交给shiroFilter管理 web环境下 创建DefaultWebSecurityManager
     *
     * @param userRealm 自定义realm
     * @return
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(ShiroRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 使用自定义Realm
        securityManager.setRealm(userRealm);

        // 关闭Shiro自带的session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        // 设置自定义Cache缓存
        securityManager.setCacheManager(new CustomCacheManager());
        return securityManager;
    }


    /**
     * 3.配置自定义的realm(用来定义验证和权限的)，作为参数交给SecurityManager管理,实现redis缓存处理
     *
     * @return
     */
    @Bean("shiroRealm")
    public ShiroRealm shiroRealm() {
        ShiroRealm shiroRealm = new ShiroRealm();
        ///开启缓存管理避免了多次反复查询数据库

        ///自定义的redis缓存也可以通过实现CacheManager做shiro缓存
        //   shiroRealm.setCacheManager(new CustomCacheManager());
        // shiroRealm.setCachingEnabled(true);   ///开启缓存
        //  shiroRealm.setAuthenticationCachingEnabled(true);  ///开启认证缓存

        ///设置认证缓存的名称,方便查找 (默认名称:authentication + 自定义realm名称)
        //  shiroRealm.setAuthenticationCacheName("authenticationCache");
        ///开启授权缓存
        //  shiroRealm.setAuthorizationCachingEnabled(true);
        ///设置授权缓存名称*/
        // shiroRealm.setAuthorizationCacheName("authorizationCache");
        return shiroRealm;
    }


    /**
     * <pre>
     * 注入bean，此处应注意 ：
     *
     * (1)代码顺序，应放置于shiroFilter后面，否则报错：
     * 	No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.
     * 	ThreadContext or as a vm static singleton. This is an invalid application configuration.
     *
     * (2)如不在此注册，在filter中将无法正常注入bean
     * </pre>
     */
  /*  @Bean("jwtFilter")
    public JwtFilter jwtFilterBean() {
        return new JwtFilter();
    }*/

    /**
     * 下面的代码是添加注解支持
     */
    @Bean
    @DependsOn({"lifecycleBeanPostProcessor" })
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        // 强制使用cglib，防止重复代理和可能引起代理出错的问题，https://zhuanlan.zhihu.com/p/29161098
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    public SimpleCookie rememberMeCookie() {
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setMaxAge(86400);
        return cookie;
    }

    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
        return cookieRememberMeManager;
    }


    @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}
